package cn.com.header.core.support.web.springmvc.converter;

import com.google.common.primitives.Ints;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * @author liangzhongqiu789@sina.com
 * @date 2017-05-18
 * @time 15:20
 */
public class OrdinalToEnumConverterFactory implements ConverterFactory<String,Enum> {

    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        return new OrdinalToEnumConverter<>(targetType);
    }

    private class OrdinalToEnumConverter<T extends Enum> implements Converter<String,T>{

        private final Class<T> enumType;

        public OrdinalToEnumConverter(Class<T> enumType){
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            if(source.isEmpty()){
                return null;
            }
            int ordinal = Ints.stringConverter().convert(source);
            return enumType.getEnumConstants()[ordinal];
        }
    }

}
